package com.cykj.pos.controller.sftdemo;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

public class MacVerifyDemo {
	static BASE64Decoder base64Decoder = new BASE64Decoder();
	
	public static void main(String[] args){
		// 按照指定顺序拼接签名串
		String signStr = "SCPCNY18205818599800575810560842655467720200911102711426554677001625363905-771770000{\"amt\":\"55.66\",\"fee\":\"0.32\",\"merchantId\":\"88038421\",\"orderId\":\"828800\",\"stlAmt\":\"55.34\",\"stlBillNo\":\"88038421210601144840269752964105\",\"stlType\":\"T0\",\"txnTime\":\"20210601144837\"}";
		// 加密后的签名串
		String sign = "WHJSuBUfRJkLmMatBbzYv1FRr4K0s74l4v1/8HNqgulJF/bv7JR0RSQWRFXerENXvAGljVg6YZyh0NFVe0kjYgfRcZpBAbbnso/QO2qz05Nr/JH/IjE34i7i/JZjaALfqWIchUHygEMbyfQzvNIKWPoapXFqqEqdn0BcgwjPzQA=";
		boolean flag = verifyMAC(sign, signStr);
		System.out.println(flag);
	}
	
	public static boolean verifyMAC(String sign, String toSignString){
		try {
			Signature sig = Signature.getInstance("SHA1WithRSA");
			Base64 base64=new Base64();  
			byte[] signed = base64.decode(sign);
			String sdpPUK_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMWAn+NszKZv2hckv495YNG3hNApCTnetywkcZM/3lm0IO7ZuIc8IjNeVXBppBr59ajhIyoAwELxzwQGo8AXHUSxQdOhBXmGFCe4ylcBoDkrqYKtK7c3+egvZ33IIGLOlua+AoBS63yV36lLdX1pdt+dhRyEISQqVCs8943G7A5QIDAQAB";
			PublicKey sdpPUK = getPublicKey(sdpPUK_key);
			sig.initVerify(sdpPUK);
			sig.update(toSignString.getBytes());
			return sig.verify(signed);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public static PublicKey getPublicKey(String key) throws Exception {
		byte[] keyBytes = base64Decoder.decodeBuffer(key);

		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}
}
